var express = require('express');
var router = express.Router();
const bcryptjs = require("bcryptjs")
const jwt = require('jsonwebtoken');

const { login, register, verify, getStores } = require("../service/storesService")
// 设置前后端接口的二级路径

// 登录
router.post('/login', async function (req, res, next) {
  // 接收前端发送过来的数据
  console.log(req.body)
  const { username, password } = req.body;   // get：req.query
  // bcryptjs加密
  const data = await login({ username, password })
  if (data) {
    // 进入 if，表示用户登录成功
    // 生成 token
    // sign 方法接收三个参数：
    // 参数一：对象，该对象为我们要保存到用户数据
    // 参数二：字符串，密钥字符串（可随意定义）
    // 参数三：对象，用于设置 token 的有效期 {expiresIn: 10 } 单位 秒
    const token = jwt.sign({ username: data.username }, 'mytoken', { expiresIn: 10 });
    res.send({ success: true, token });
  } else {
    res.send({ success: false });
  }
});
// 注册
router.post('/register', async function (req, res, next) {
  const { username, password } = req.body;   // get：req.query
  // // const newPassword = getMd5(password)
  const newPassword = bcryptjs.hashSync(password, 10)
  console.log(newPassword)
  const data = await register({ username, password: newPassword })
  // const data = await register(user)
  res.send(data)
});

//验证
router.post('/verify', async function (req, res, next) {
  const user = req.body;
  const data = await verify(user)
  res.send(data)
});

router.get('/isLogin', async function (req, res, next) {
  // 获取 token
  const token = req.get('Authorization');
  const { username } = jwt.verify(token.split(" ")[1], 'mytoken');
  res.send({ username: username });
})

// 
router.get("/getStores", async function (req, res, next) {
  console.log(req.query)
  const data = await getStores()
  // console.log("111111111店铺",data)
  res.send(data)
})


module.exports = router;
